package com.zw.cloud.tools.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.condition.PathPatternsRequestCondition;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import org.springframework.web.util.pattern.PathPattern;

import javax.annotation.PostConstruct;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Component
public class UriUtils {

    @Autowired
    WebApplicationContext applicationContext;

    public static List<String> uriList = new ArrayList<>(100);
    @PostConstruct
    public void getAllUri() {
        RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
        // 拿到Handler适配器中的全部方法
        Map<RequestMappingInfo, HandlerMethod> methodMap = mapping.getHandlerMethods();
        for (RequestMappingInfo info : methodMap.keySet()){
            PathPatternsRequestCondition pathPatternsCondition = info.getPathPatternsCondition();
            Set<RequestMethod> methods = info.getMethodsCondition().getMethods();
            for (RequestMethod method : methods) {
                if (Objects.nonNull(pathPatternsCondition)) {
                    Set<PathPattern> patterns = pathPatternsCondition.getPatterns();
                    if (CollectionUtils.isEmpty(patterns)) {
                        continue;
                    }
                    uriList.addAll(patterns.stream().map(pathPattern -> {
                        String patternString = pathPattern.getPatternString();
                        if (patternString.startsWith("/")) {
                            return method + patternString;
                        }
                        return method + "/" + patternString;
                    }).collect(Collectors.toList()));
                }
            }
        }
        log.info("[UriUtils][getAllUri]urlList is {}",uriList);
    }
}
